<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="论文标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入论文标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发表时间" prop="postedTime">
        <el-date-picker
          v-model="queryParams.postedTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="发表刊物/论文集" prop="publications">
        <el-input
          v-model="queryParams.publications"
          placeholder="请输入发表刊物/论文集"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所属单位" prop="affiliation">
        <el-select
          v-model="queryParams.affiliation"
          placeholder="请选择所属单位"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.AFFILIATION)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 修改为作者及贡献率合并搜索 -->
      <el-form-item label="作者及贡献率" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="佐证地址" prop="evidenceUrl">
        <el-input
          v-model="queryParams.evidenceUrl"
          placeholder="请输入佐证地址"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="作者类型" prop="authorType">
        <el-select
          v-model="queryParams.authorType"
          placeholder="请选择作者类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.AUTHOR_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 删除贡献率搜索字段 -->
      <el-form-item label="论文类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择论文类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.THESIS_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['digital:thesis:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['digital:thesis:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="论文标题" align="center" prop="title" />
      <!-- 合并作者和贡献率字段 -->
      <el-table-column 
        label="作者" 
        align="center" 
        min-width="200"
      >
        <template #default="scope">
          <div v-if="scope.row.authorWithRateList" class="flex flex-wrap justify-center gap-1">
            <el-tag 
              v-for="(item, index) in scope.row.authorWithRateList" 
              :key="index" 
              size="small"
              effect="plain"
              type="info"
              class="m-1"
            >
              {{ item }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="作者类型" align="center" prop="authorType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.AUTHOR_TYPE" :value="scope.row.authorType" />
        </template>
      </el-table-column>
      <el-table-column label="论文类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.THESIS_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="所属单位" align="center" prop="affiliation">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.AFFILIATION" :value="scope.row.affiliation" />
        </template>
      </el-table-column>
      <el-table-column label="发表刊物/论文集" align="center" prop="publications" />
      <el-table-column 
        label="佐证" 
        align="center" 
        prop="evidenceUrl" 
        min-width="150"
      >
        <template #default="scope">
          <div 
            v-if="scope.row.evidenceUrl && Array.isArray(scope.row.evidenceUrl)"
            class="flex flex-wrap justify-center gap-1"
          >
            <el-link
              v-for="(url, index) in scope.row.evidenceUrl"
              :key="index"
              type="primary"
              :href="url"
              target="_blank"
              :underline="false"
              class="inline-block"
            >
              佐证{{ index + 1 }}
            </el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="发表时间"
        align="center"
        prop="postedTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['digital:thesis:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['digital:thesis:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ThesisForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ThesisApi, ThesisVO } from '@/api/digital/thesis'
import ThesisForm from './ThesisForm.vue'
import { ElTag } from 'element-plus'

/** 论文 列表 */
defineOptions({ name: 'Thesis' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ThesisVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  title: undefined,
  postedTime: [],
  publications: undefined,
  affiliation: undefined,
  author: undefined,        // 仅用于作者搜索
  evidenceUrl: undefined,   // 不再支持数组搜索
  authorType: undefined,
  // 删除贡献率搜索条件
  type: undefined,
  reserved1: undefined,
  reserved2: undefined,
  reserved3: undefined,
  reserved4: undefined,
  reserved5: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ThesisApi.getThesisPage(queryParams)
    // 处理 evidenceUrl 字段为数组
    data.list.forEach(item => {
      if (typeof item.evidenceUrl === 'string') {
        // 去除首尾中括号并按逗号分割
        let arr = item.evidenceUrl
          .replace(/^\[|\]$/g, '')
          .split(',')
          .map(s => s.trim().replace(/^"|"$/g, ''))
          .filter(url => url);
        item.evidenceUrl = arr;
      }
      // 如果 evidenceUrl 还是 undefined/null，设为空数组
      if (!Array.isArray(item.evidenceUrl)) {
        item.evidenceUrl = [];
      }
      
      // 合并作者和贡献率字段
      const authorList = item.author ? item.author.split(',') : []
      const rateList = item.rate ? item.rate.split(',') : []
      
      // 创建新字段：authorWithRateList
      item.authorWithRateList = []
      
      // 确保两者长度一致
      const maxLength = Math.max(authorList.length, rateList.length)
      for (let i = 0; i < maxLength; i++) {
        const author = authorList[i] || ''
        const rate = rateList[i] || '0'
        // 格式：作者(贡献率%)
        item.authorWithRateList.push(`${author}(${rate}%)`)
      }
    });
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ThesisApi.deleteThesis(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ThesisApi.exportThesis(queryParams)
    download.excel(data, '论文.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
/* 添加作者及贡献率的标签样式 */
.el-tag {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>